import React, { useState, useEffect, useRef } from 'react';
import './TextToSpeech.css';

interface TextToSpeechProps {
  text?: string;
  autoPlay?: boolean;
  onSpeakStart?: () => void;
  onSpeakEnd?: () => void;
  onSpeakError?: (error: string) => void;
  className?: string;
  style?: React.CSSProperties;
}

interface VoiceSettings {
  rate: number;
  pitch: number;
  volume: number;
  voice: SpeechSynthesisVoice | null;
}

const TextToSpeech: React.FC<TextToSpeechProps> = ({
  text = '',
  autoPlay = false,
  onSpeakStart,
  onSpeakEnd,
  onSpeakError,
  className = '',
  style = {}
}) => {
  const [isSpeaking, setIsSpeaking] = useState(false);
  const [isPaused, setIsPaused] = useState(false);
  const [availableVoices, setAvailableVoices] = useState<SpeechSynthesisVoice[]>([]);
  const [settings, setSettings] = useState<VoiceSettings>({
    rate: 1,
    pitch: 1,
    volume: 1,
    voice: null
  });
  const [showSettings, setShowSettings] = useState(false);
  const [inputText, setInputText] = useState(text);
  const utteranceRef = useRef<SpeechSynthesisUtterance | null>(null);

  // 初始化语音合成
  useEffect(() => {
    const initSpeechSynthesis = () => {
      if ('speechSynthesis' in window) {
        const voices = window.speechSynthesis.getVoices();
        setAvailableVoices(voices);
        
        // 选择默认的中文语音
        const chineseVoice = voices.find(voice => 
          voice.lang.includes('zh') || voice.lang.includes('cmn')
        );
        
        setSettings(prev => ({
          ...prev,
          voice: chineseVoice || voices[0] || null
        }));
        
        // 监听语音状态变化
        window.speechSynthesis.onvoiceschanged = () => {
          const updatedVoices = window.speechSynthesis.getVoices();
          setAvailableVoices(updatedVoices);
          
          if (!settings.voice) {
            const chineseVoice = updatedVoices.find(voice => 
              voice.lang.includes('zh') || voice.lang.includes('cmn')
            );
            setSettings(prev => ({
              ...prev,
              voice: chineseVoice || updatedVoices[0] || null
            }));
          }
        };
      }
    };

    initSpeechSynthesis();
  }, [settings.voice]);

  // 当text prop变化时更新输入文本
  useEffect(() => {
    setInputText(text);
  }, [text]);

  // 自动播放
  useEffect(() => {
    if (autoPlay && text && !isSpeaking) {
      speakText(text);
    }
  }, [autoPlay, text, isSpeaking]);

  const speakText = (textToSpeak: string) => {
    if (!textToSpeak.trim() || !('speechSynthesis' in window) || !settings.voice) {
      return;
    }

    // 停止当前播放
    stopSpeaking();
    
    const utterance = new SpeechSynthesisUtterance(textToSpeak);
    utterance.voice = settings.voice;
    utterance.rate = settings.rate;
    utterance.pitch = settings.pitch;
    utterance.volume = settings.volume;
    utterance.lang = settings.voice.lang;
    
    utteranceRef.current = utterance;
    
    utterance.onstart = () => {
      setIsSpeaking(true);
      setIsPaused(false);
      onSpeakStart?.();
    };
    
    utterance.onend = () => {
      setIsSpeaking(false);
      setIsPaused(false);
      utteranceRef.current = null;
      onSpeakEnd?.();
    };
    
    utterance.onerror = (event) => {
      console.error('语音合成错误:', event);
      setIsSpeaking(false);
      setIsPaused(false);
      utteranceRef.current = null;
      onSpeakError?.(event.error);
    };
    
    window.speechSynthesis.speak(utterance);
  };

  const pauseSpeaking = () => {
    if ('speechSynthesis' in window && isSpeaking) {
      window.speechSynthesis.pause();
      setIsPaused(true);
    }
  };

  const resumeSpeaking = () => {
    if ('speechSynthesis' in window && isPaused) {
      window.speechSynthesis.resume();
      setIsPaused(false);
    }
  };

  const stopSpeaking = () => {
    if ('speechSynthesis' in window) {
      window.speechSynthesis.cancel();
      setIsSpeaking(false);
      setIsPaused(false);
      utteranceRef.current = null;
    }
  };

  const handleSpeak = () => {
    speakText(inputText);
  };

  const handleSettingsChange = (key: keyof VoiceSettings, value: any) => {
    setSettings(prev => ({
      ...prev,
      [key]: value
    }));
  };

  return (
    <div className={`text-to-speech ${className}`} style={style}>
      {/* 文本输入区域 */}
      <div className="tts-input-container">
        <textarea
          value={inputText}
          onChange={(e) => setInputText(e.target.value)}
          placeholder="输入要转换的文字..."
          className="tts-textarea"
          rows={4}
        />
      </div>

      {/* 控制按钮 */}
      <div className="tts-controls">
        <button
          className={`tts-btn ${isSpeaking ? 'speaking' : ''}`}
          onClick={isSpeaking ? stopSpeaking : handleSpeak}
          title={isSpeaking ? "停止播放" : "开始播放"}
        >
          <span>{isSpeaking ? '⏹️' : '🔊'}</span>
        </button>

        {isSpeaking && (
          <button
            className={`tts-btn ${isPaused ? 'paused' : ''}`}
            onClick={isPaused ? resumeSpeaking : pauseSpeaking}
            title={isPaused ? "继续播放" : "暂停播放"}
          >
            <span>{isPaused ? '▶️' : '⏸️'}</span>
          </button>
        )}

        <button
          className="tts-btn settings-btn"
          onClick={() => setShowSettings(!showSettings)}
          title="语音设置"
        >
          <span>⚙️</span>
        </button>
      </div>

      {/* 语音设置面板 */}
      {showSettings && (
        <div className="tts-settings">
          <h4>语音设置</h4>
          
          <div className="setting-item">
            <label>语速:</label>
            <input
              type="range"
              min="0.5"
              max="2"
              step="0.1"
              value={settings.rate}
              onChange={(e) => handleSettingsChange('rate', Number(e.target.value))}
              className="setting-slider"
            />
            <span>{settings.rate}x</span>
          </div>

          <div className="setting-item">
            <label>音调:</label>
            <input
              type="range"
              min="0.5"
              max="2"
              step="0.1"
              value={settings.pitch}
              onChange={(e) => handleSettingsChange('pitch', Number(e.target.value))}
              className="setting-slider"
            />
            <span>{settings.pitch}x</span>
          </div>

          <div className="setting-item">
            <label>音量:</label>
            <input
              type="range"
              min="0"
              max="1"
              step="0.1"
              value={settings.volume}
              onChange={(e) => handleSettingsChange('volume', Number(e.target.value))}
              className="setting-slider"
            />
            <span>{Math.round(settings.volume * 100)}%</span>
          </div>

          <div className="setting-item">
            <label>语音:</label>
            <select
              value={settings.voice?.name || ''}
              onChange={(e) => {
                const voice = availableVoices.find(v => v.name === e.target.value);
                handleSettingsChange('voice', voice || null);
              }}
              className="setting-select"
            >
              {availableVoices.map((voice, index) => (
                <option key={index} value={voice.name}>
                  {voice.name} ({voice.lang})
                </option>
              ))}
            </select>
          </div>
        </div>
      )}

      {/* 状态指示器 */}
      {isSpeaking && (
        <div className="tts-status">
          <div className="status-indicator">
            <span className="status-dot"></span>
            <span className="status-text">
              {isPaused ? '已暂停' : '正在播放...'}
            </span>
          </div>
        </div>
      )}
    </div>
  );
};

export default TextToSpeech; 